Iteterables II - Code Cards

Try me

Open In ColabBinder

How to use

  • Each card mirrors an A4 classroom prompt. Predict first (or discuss), then run the cell to check.

  • Detective cards show a buggy idea in Markdown; the code cell shows a fixed version.

  • Keep explanations short and schematic (whatwhy).

Turn Gemini into a coding tutor (no direct answers)

Paste this in your first chat with Gemini to keep it in “tutor mode”:

You are a **coding tutor** for Python in Jupyter/Colab. Follow the **course motto** “do not give up learning.”

### Role & Goals
- Use **Socratic guidance** and **test-first thinking** to help me solve problems myself.
- Help me read errors, reason about state, and make small, safe iterations.

### Strict Rules
1) **Do not** provide full working solutions or paste complete functions/programs.
   - You may show **tiny illustrative fragments (≤3 lines)** or **pseudo-code with TODOs**, but not a drop-in answer.
2) Prefer **questions over answers**; offer **one small next step** at a time.
3) When debugging, explain **what the traceback says**, give **2–3 hypotheses**, and propose the **smallest diff** in *plain English* first.
4) Encourage **TDD**: ask me to write/assert a test, predict, run, and report outputs.
5) Keep responses concise (≈120–150 words) unless I ask for a deeper explanation or code review.
6) Ask me to **run code and share results**; adapt based on the output.
7) If I request the full solution, remind me of the rules and offer a **higher-tier hint** instead.
8) When I finalize an exercise, reinforce learning lessons and suggest additional exercises

### Interaction Loop (use this structure)
- **Restate goal:** what I’m trying to accomplish in one line.
- **Diagnose:** key assumption to check or error to interpret.
- **Hint (tiered):**
  - Tier 1: Conceptual nudge (no code).
  - Tier 2: Directed hint (identify line/construct to change).
  - Tier 3: Pseudo-code with TODOs or a **1–3 line** pattern (still not a full solution).
- **Next action:** one concrete step for me to try now.
- **Ask back:** what to run/paste (output, test result, or traceback).

### When reviewing my code
- Comment on **correctness, clarity, naming, and complexity (big-O)**.
- Suggest **tests** I’m missing (boundaries, empty cases, error paths).

### Safety & Ethics
- No secrets or private data in prompts.
- avoid library functions/APIs unless I ask.

Stay in tutor mode for the whole session.

Code Cards

  1. Does any statement raise an exception? (Explain why)

t = ("A", "B", "C")
y = ["D", "E", "F"]
y = y + ["G"]
t[0] = "Z"
[ ]:

  1. Does any statement raise an exception? (Explain why)

t = ("A", "B", "C")
a = t[0]
a += "DD"
t[0] = "Z"
[ ]:

  1. Given:

real_names = {"Homelander": "John", "Queen Maeve": "Maggie", "A-Train": "Reggie", "Starlight": "Annie"}

Choose all expressions below that evaluate to True:

"A-Train" in real_names
"John" in real_names
"Maggie" in real_names.values()
"Annie" in real_names.items()
[ ]:

  1. Given:

supes = {"Homelander": {"real_name": "John", "power_level": 100},
         "Queen Maeve": {"real_name": "Maggie", "power_level": 85},
         "A-Train": {"real_name": "Reggie", "power_level": 75},
         "Starlight": {"real_name": "Annie", "power_level": 80}}

Choose all expressions below that evaluate to True:

"power_level" in supes["A-Train"]
"Reggie" in supes["A-Train"].values()
"Annie" in supes["Starlight"].keys()
supes["Homelander"]["power_level"] < supes["Queen Maeve"]["power_level"]
[ ]:

  1. Given:

students = {"001": {"name": "Peter Parker", "grades": [85, 90, 78]},
            "002": {"name": "Jean Grey", "grades": [88, 76, 92]},
            "003": {"name": "Alonzo Thompson", "grades": [95, 85, 87]}}

Select the best way to iterate through the students dictionary to calculate and print each student’s average grade together with their id and name. Motivate your response.

# Option A
for student_id in students:
    info = students[student_id]
    for grade in info["grades"]:
        avg_grade = sum(info["grades"]) / len(info["grades"])
    print(f"ID: {student_id}, Name: {info['name']}, Average Grade: {avg_grade:.2f}")
# Option B
for student_id, info in students.items():
    avg_grade = sum(info["grades"]) / len(info["grades"])
    print(f"ID: {student_id}, Name: {info['name']}, Average Grade: {avg_grade:.2f}")

# Option C
for info in students.values():
    avg_grade = sum(info["grades"]) / len(info["grades"])
    print(f"Name: {info['name']}, Average Grade: {avg_grade:.2f}")
[ ]:

  1. Given:

students = {"001": {"name": "Peter Parker", "grades": [85, 90, 78]},
            "002": {"name": "Jean Grey", "grades": [88, 76, 92]},
            "003": {"name": "Alonzo Thompson", "grades": [95, 85, 87]}}

Predict the output of the following code snippet:

print(students["002"]["grades"][1])
print(len(students))
print("Jean Grey" in students["002"])
[ ]:

  1. Given:

supes = {"Homelander": {"real_name": "John", "power_level": 100},
         "Queen Maeve": {"real_name": "Maggie", "power_level": 85},
         "A-Train": {"real_name": "Reggie", "power_level": 75},
         "Starlight": {"real_name": "Annie", "power_level": 80}}

Predict the output of the following code snippet:

print(supes["Startlight"]["power_level"])
print(supes["A-Train"]["real_name"])
for supe in supes:
    if supes[supe]["power_level"] > 80:
        print(f"{supe} is powerful")
[ ]:

  1. Given:

pilots = [{"name": "Han Solo", "ship": "Millennium Falcon", "speed": 1050, "badges": ["Smuggler", "Gunner"]},
          {"name": "Luke Skywalker", "ship": "X-Wing", "speed": 950, "badges": ["Jedi", "Pilot"]},
          {"name": "Darth Vader", "ship": "TIE Fighter", "speed": 900, "badges": ["Sith Lord", "Commander"]}]

Select the best way to iterate through the pilots list to print each pilot’s name, ship, and badges. Motivate your response.

# Option A
for pilot in pilots:
    print(f"Name: {pilot['name']}, Ship: {pilot['ship']}, Badges: {', '.join(pilot['badges'])}")
# Option B
for i in range(len(pilots)):
    pilot = pilots[i]
    print(f"Name: {pilot['name']}, Ship: {pilot['ship']}, Badges: {', '.join(pilot['badges'])}")
# Option C
for pilot in pilots:
    for k, v in pilot.items():
        print(f"{k}: {v}")
[ ]:

  1. Predict the output of the following code snippet:

pilots = [{"name": "Han Solo", "ship": "Millennium Falcon", "speed": 1050, "badges": ["Smuggler", "Gunner"]},
          {"name": "Luke Skywalker", "ship": "X-Wing", "speed": 950, "badges": ["Jedi", "Pilot"]},
          {"name": "Darth Vader", "ship": "TIE Fighter", "speed": 900, "badges": ["Sith Lord", "Commander"]}]
print(pilots[1]["badges"][0])
print(pilots[2]["speed"] > pilots[0]["speed"])
print(len(pilots[0]["badges"][1]))
[ ]:

  1. Which of the following snippets produces the same result as the others?

# Option A
series = []
for i in range(10):
    if i > 0 and i % 3 == 0:
        series.append(1/i**3)
print(series)

# Option B
series = [i%3 == 0 for i in range(10) if i > 0 and 1/i**3 == 0]
print(series)

# Option C
series = [1/i**3 for i in range(10) if i > 0 and i % 3 == 0]
print(series)

# Option D
series = [1/i**3 if i > 0 and i % 3 == 0 else 0 for i in range(10)]
print(series)
[ ]:

  1. What is the series of numbers generated by the following code snippet? Briefly explain how it works.

s = [i**2 for i in range(5) if i % 2 == 0]

A The series is: [0, 1, 4, 9, 16]

B The series is: [1, 4, 9, 16, 25]

C The series is: [0, 4, 16]

D The series is Fall Out season 3 premiering November 2026.

[ ]:

  1. What is the series of numbers generated by the following code snippet? Briefly explain how it works.

fib = [0, 1] + [fib.append(sum(fib[-2:])) for _ in range(5)]

A The series is: [0, 1, 2, 3, 4, 5, 6]

B The series is: [0, 1, 1, 2, 3, 5, 8]

C The series is: [0, 1, 1, 2, 4, 8, 16

D The code raises an exception.

[ ]:

  1. What is the series of numbers generated by the following code snippet? Briefly explain how it works.

series = [2**i for i in range(6) if i % 2 == 1]

A The series is: [1, 2, 4, 8, 16, 32]

B The series is: [2, 8, 32]

C The series is: [2, 4, 6, 8, 10]

D The code raises an exception.

[ ]: